#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include "domain_parse.h"


/*调用函数成功返回一个hostent结构体
struct hostent
{
	char *h_name;//主机规范名
	char ** h_aliases;//别名
	short h_addrtype;//主机IP地址的类型ipv4/ipv6
	short h_length;//主机ip地址的长度
	char ** h_addr_list;//表示的是主机的ip地址，
	//这个是以网络字节序存储的。
	//需要调用inet_ntop();
};
*/

#define ALL_IP 0//打印所有ip

/*
int main(int argc,char **argv)
{
	char* hostname = "172.18.18.168";
	char ip[16] = {0};

	DNS("www.latelee.com", ip);
	printf("dddd: %s\n", ip);

	DNS("www.baidu.com", ip);
	printf("dddd: %s\n", ip);

	DNS("latelee-wordpress", ip);
	printf("dddd: %s\n", ip);

	DNS("172.18.18.18", ip);
	printf("dddd: %s\n", ip);
} 		

int DNS(char *domain, char*ipaddr)
{
	struct hostent *host;

	if(!domain || !ipaddr)
	{
		return -1;
	}

	host = gethostbyname(domain);
	if(!host)
	{
		return -1;
	}
	strncpy(ipaddr, inet_ntoa(*(struct in_addr*)host->h_addr),16);

#if ALL_IP
	for(int i = 0; host->h_addr_list[i]; i++)
	{
		printf("%d ip:%s\n",i,inet_ntoa(*(struct in_addr*)host->h_addr[i]));

	}
#endif

	return 0;
}

*/
char* DNS(char *domain)
{
	struct hostent *host;

	if(!domain)
	{
		return NULL;
	}

	host = gethostbyname(domain);
	if(!host)
	{
		return NULL;
	}
//	strncpy(ipaddr, inet_ntoa(*(struct in_addr*)host->h_addr),16);

#if ALL_IP
	for(int i = 0; host->h_addr_list[i]; i++)
	{
		printf("%d ip:%s\n",i,inet_ntoa(*(struct in_addr*)host->h_addr[i]));

	}
#endif

	return inet_ntoa(*(struct in_addr*)host->h_addr);
}

